import dayjs from 'dayjs'
import { router } from '@/router'
import { RouteLocationNormalizedLoaded } from 'vue-router'
import { useIntervalFn } from '@vueuse/core';

class App {

  /** 路由器 */
  public get router() {
    return router
  }

  /** 路由信息 */
  public get route(): RouteLocationNormalizedLoaded {
    let data: any = { path: '', meta: {}, params: {}, query: {} }
    const jsonStr = sessionStorage.getItem('route')
    if (jsonStr) data = JSON.parse(jsonStr)
    return data
  }

  /** 日期格式化 */
  public dateFormat(time: string | number | Date, format: string = 'YYYY-MM-DD HH:mm') {
    return dayjs(time).format(format)
  }

  /** 获取Url变量 */
  public getUrlVariable(variable: string) {
    const query = window.location.search.substring(1).replace('/', '')
    const vars = query.split('&');
    for (let i = 0; i < vars.length; i++) {
      const pair = vars[i].split('=')
      if (pair[0] == variable) return pair[1]
    }
    return undefined
  }

  /** 复制内容到到剪贴板 */
  public copyToClipboard(str: string): Promise<boolean> {
    return new Promise((resolve, reject) => {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(str)
          .then(() => resolve(true))
          .catch(err => reject(err))
      } else {
        let textArea = document.createElement('textarea')
        textArea.value = str
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        try {
          let successful = document.execCommand('copy')
          if (successful == true) resolve(true)
          else resolve(false)
        } catch (err) {
          reject(err)
        }
        document.body.removeChild(textArea)
      }
    })
  }

  /**倒计时 */
  public useCounter() {
    const count = ref(0);
    // resume - 继续，pause - 暂停， isActive - 是否执行中(isActive.value)
    const { resume, pause, isActive } = useIntervalFn(
      () => {
        count.value--;
        if (count.value === 0) {
          pause();
        }
      },
      1000,
      { immediate: false }
    );
    const start = (startTime = 60) => {
      if (isActive.value) return;
      // 因为初始值已经重置,所以继续执行,可以理解为 重新开始
      count.value = startTime;
      resume();
    };
    // 页面要用到的数据，都返回
    return { count, resume, pause, isActive, start };
  };

  /**判断浏览器 */
  public isWeChat(): boolean {
    //window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
    return /MicroMessenger/i.test(window.navigator.userAgent);
  }

  /** 根据姓名生成背景色头像 */
  public nameAvatar(name: string): string {
    var temp = [];
    temp.push("#");
    for (let index = 0; index < name.length; index++) {
      temp.push(parseInt(name[index].charCodeAt(0), 10).toString(16));
    }
    return temp.slice(0, 5).join('').slice(0, 4);
  }
}

export const app = new App()
